#include "ScriptManager.h"

#include "Sprite.h" // for exporting

/// look to GameManager.cpp for info on _instance and instance()
ScriptManager* ScriptManager::_instance = NULL;
ScriptManager* ScriptManager::instance()
{
    if(!_instance)
        _instance = new ScriptManager();
    return _instance;
}

/// opens lua and luabind libs
ScriptManager::ScriptManager()
{
    _luaState = lua_open();
    luaL_openlibs(_luaState);
    luabind::open(_luaState);
}

/// closes lua
ScriptManager::~ScriptManager()
{
    lua_close(_luaState);
}

/// returns the lua state
lua_State* ScriptManager::luaState()
{
    return _luaState;
}

/// loads and calls a lua file
// #define luaL_dofile(L, fn) \
//      n n (luaL_loadfile(L, fn) || lua_pcall(L, 0, LUA_MULTRET, 0))
void ScriptManager::runScript(std::string name)
{
    luaL_dofile(_luaState, name.c_str());
}

/// exports all class info/functions to lua
void ScriptManager::exportToLua()
{
    using namespace luabind;

    module(_luaState)
    [
        class_<Sprite>("Sprite")
            .def(constructor<>())
            .def("load", (void (Sprite::*)(std::string))&Sprite::load)
            .def("load", (void (Sprite::*)(std::string, float, float, float, float, float, float))&Sprite::load)
            .def("setPosition", (void (Sprite::*)(float, float))&Sprite::setPosition)
            .def("move", &Sprite::move)
            .def("setClip", (void (Sprite::*)(float, float, float, float))&Sprite::setClip)
    ];

}
